/**
 * 重载位置计算（位置居中问题）
 * @param el
 * @param offset
 * @param scale
 */
function setTransform(el, offset, scale) {
    const pos = offset || new L.Point(0, 0);
    el.style[L.DomUtil.TRANSFORM] =
        (L.Browser.ie3d
            ? "translate(" + pos.x + "px," + pos.y + "px,0) translateX(-50%)"
            : "translate3d(" + pos.x + "px," + pos.y + "px,0) translateX(-50%)") +
        (scale ? " scale(" + scale + ")" : "");
}

/**
 * 重载样式设置
 * @param el
 * @param point
 */
function setPosition(el, point) {
    el._leaflet_pos = point;
    if (L.Browser.any3d) {
        setTransform(el, point);
    } else {
        el.style.left = point.x + "px";
        el.style.top = point.y + "px";
    }
}

L.CustomPopup = L.Popup.extend({
    _initLayout: function() {
        const prefix = "leaflet-popup",
            container = (this._container = L.DomUtil.create(
                "div",
                prefix + " " + (this.options.className || "") + " leaflet-zoom-animated"
            ));
        const wrapper = container;
        this._contentNode = L.DomUtil.create("div", prefix + "-content", wrapper);
        // 覆盖默认颜色
        // this._contentNode.style.width = auto;
        this._contentNode.style.margin = 0;
        L.DomEvent.disableClickPropagation(wrapper)
            .disableScrollPropagation(this._contentNode)
            .on(wrapper, "contextmenu", L.DomEvent.stopPropagation);
        this._tipContainer = L.DomUtil.create(
            "div",
            prefix + "-tip-container",
            container
        );
        this._tip = L.DomUtil.create("div", prefix + "-tip", this._tipContainer);
    },
    // 位置更新
    _updatePosition: function() {
        if (!this._map) {
            return;
        }
        let pos = this._map.latLngToLayerPoint(this._latlng),
            offset = L.point(this.options.offset),
            anchor = [0, 0];
        if (this._zoomAnimated) {
            setPosition(this._container, pos.add(anchor));
        } else {
            offset = offset.add(pos).add(anchor);
        }
        const bottom = (this._containerBottom = -offset.y),
            left = (this._containerLeft =
                -Math.round(this._containerWidth / 2) + offset.x);
        this._container.style.bottom = bottom + "px";
        this._container.style.left = left + "px";
    },
    // 重写层级变化触发更新
    _animateZoom: function(e) {
        const pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center),
            anchor = [0, 0];
        setPosition(this._container, pos.add(anchor));
    },
    setOffset: function (offset) {
        this.options.offset = offset;
        return this.update();
    },
});

export default L.CustomPopup
